import React , { useState,useEffect }from 'react';
import { Form, Input, Upload, Button, Avatar, Space, message  } from 'antd';
import { UserOutlined, UploadOutlined } from '@ant-design/icons';
import { updateUser } from '../../../../apis/public/user'; //
import { Editor_Default_Directory } from '@/globals/document';
import { uploadFile } from '../../../../apis/public/upload';

const BasicInfo: React.FC = () => {

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [avatar, setAvatar] = useState<string>();

  // 从 localStorage 获取用户数据并设置表单初始值
  useEffect(() => {
    const userInfoStr = localStorage.getItem('userInfo');
    if (userInfoStr) {
      try {
        let user = JSON.parse(userInfoStr).user;
        form.setFieldsValue({
          username: user.username,
          email: user.email,
          phone: user.phone,
        });
        if(user.avatar){
          let avatarUrl = `/api/starhub/document/download/${user.avatar}`;
          setAvatarUrl(avatarUrl);
        }
      } catch (error) {
        console.error('解析用户数据失败:', error);
      }
    }
  }, [form]); // 依赖 form 确保只执行一次

  // 提交处理
  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      const response = await updateUser({
        username: values.username,
        email: values.email,
        phone: values.phone,
        avatar:avatar,
      });
      message.success('更新成功');
      // form.resetFields(); // 清空表单
    } catch (error) {
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return Upload.LIST_IGNORE;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB！');
      return Upload.LIST_IGNORE;
    }
    return true; // 验证通过，允许上传
  };

  const customRequest = async (options: any) => {
    try {
      // 本地预览
      const reader = new FileReader();
      reader.readAsDataURL(options.file);
      reader.onload = () => {
        setAvatarUrl(reader.result as string);
      };
      
      // 拼接文件上传参数
      const formData = new FormData();
      formData.append('file', options.file);
      formData.append('fileName', options.file instanceof File ? options.file.name : 'unknown');
      formData.append('uid', options.file?.uid);
      formData.append('directoryId', Editor_Default_Directory.toString());
      const response = await uploadFile(formData);

      if (options.onSuccess) {
        let avatarUrl = `/api/starhub/document/download/${response.data.page?.[0].id}`;
        setAvatar(response.data.page?.[0].id);
        setAvatarUrl(avatarUrl);
        options.onSuccess(response);
      }
      //文件内容提取
      //onUploadSuccess(file); // 调用上传成功回调函数
    } catch (error) {
      if (options.onError) {
        options.onError(error instanceof Error ? error : new Error('上传失败'));
      }
    }
  };
  
  return (
    <div style={{ padding: '20px' }}>
      <Form form={form} layout="vertical">
        <Form.Item label="头像" name="avatar"  >
          <Space direction="vertical" align="center">
            <Avatar 
              size={100} 
              src={avatarUrl} 
              icon={<UserOutlined />}
            />
             <Upload
                beforeUpload={beforeUpload}
                maxCount={1}
                customRequest={(options) => {customRequest(options)}}
                showUploadList={false}
                onRemove={()=> { }}
                accept=".png, .jpeg, .jpg, .gif, .bmp, .tiff, .svg, .webp, .ico, .psd, .raw, .heic, .heif"
              >
                <Button icon={<UploadOutlined />}>上传头像</Button>
              </Upload>
          </Space>
        </Form.Item>
        
        <Form.Item label="用户名" name="username">
          <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item label="邮箱" name="email">
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        <Form.Item label="手机号" name="phone">
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item>
          <Button 
          onClick={handleSubmit} 
          loading={loading}
          disabled={loading}
          type="primary">保存修改</Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default BasicInfo; 